import requests
import time
import pymongo
import csv

# 1718960107150
# 1718960553559
# 1718960513186.2256
# 1718960494.730256
# print(int(time.time()*1000))
current_time = int(time.time() * 1000)
# with open('东方财富.csv', 'w', encoding='utf8', newline='') as csvfile:
#     csvwriter = csv.writer(csvfile)
#     csvwriter.writerow(["代码", "股票名", "最新价", "最低价"])
client = pymongo.MongoClient(host="localhost", port=27017)
client.drop_database("donngfangcaifu")
db = client.get_database("donngfangcaifu")
collection = db.create_collection("股票信息")

for i in range(1, 10):
    print(f"当前第{i}页")
    url = f"https://97.push2.eastmoney.com/api/qt/clist/get?pn={i}&pz=20&po=1&np=1&ut=bd1d9ddb04089700cf9c27f6f7426281&fltt=2&invt=2&dect=1&wbp2u=|0|0|0|web&fid=f3&fs=m:0+t:6,m:0+t:80,m:1+t:2,m:1+t:23,m:0+t:81+s:2048&fields=f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f12,f13,f14,f15,f16,f17,f18,f20,f21,f23,f24,f25,f22,f11,f62,f128,f136,f115,f152&_={current_time}"
    response = requests.get(url)
    datas = response.json()["data"]["diff"]
    l = []
    for data in datas:
        print(f"当前读取的是{data['f14']}")
        # csvwriter.writerow()
        d = {
             "代码": data['f12'],
             "股票名": data['f14'],
             "最新价": data['f3'],
             "最低价": data['f17']
        }
        l.append(d)
        time.sleep(0.2)
    collection.insert_many(l)
client.close()
